package com.dlwx.firefighting.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dlwx.firefighting.R;
import com.dlwx.firefighting.adapter.CartAdapter;
import com.dlwx.firefighting.adapter.ProductAdapter;
import com.dlwx.firefighting.bean.CartBean;
import com.dlwx.firefighting.bean.GoodsBean;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.inter.CartInter;
import com.dlwx.firefighting.utils.DialogUtils;
import com.dlwx.firefighting.utils.LogUtils;
import com.dlwx.firefighting.utils.SPUtils;
import com.dlwx.firefighting.utils.ToastUtils;
import com.dlwx.firefighting.views.GridSpacingItemDecoration;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.view.CommonHeader;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


public class CartFragment extends Fragment implements CartInter {

    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.cart_recycler)
    LRecyclerView cartRecycler;
    @BindView(R.id.tv_choose)
    TextView tvChoose;
    @BindView(R.id.money_tv)
    TextView moneyTv;
    @BindView(R.id.commit_tv)
    TextView commitTv;
    @BindView(R.id.commit_ll)
    LinearLayout commitLl;
    @BindView(R.id.toshoping_tv)
    TextView toshopingTv;
    Unbinder unbinder;
    @BindView(R.id.image_xfsc)
    ImageView imageXfsc;
    @BindView(R.id.ll_xfsc)
    LinearLayout llXfsc;
    @BindView(R.id.tv_xfsc)
    TextView tvXfsc;
    @BindView(R.id.tv_edit)
    TextView tvEdit;
    private String mParam1;
    private String mParam2;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private CartAdapter cartAdapter;
    private List<CartBean> datas = new ArrayList<>();
    private List<CartBean> choseDatas = new ArrayList<>();
    private boolean isChooseALL = false;
    private String userId;
    private int page = 1;
    private int requestNum = 10;
    private int count = 0;

    private OnFragmentInteractionListener mListener;
    private LRecyclerViewAdapter footerLRecyclerViewAdapter;

    public CartFragment() {

    }

    public static CartFragment newInstance(String param1, String param2) {
        CartFragment fragment = new CartFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for getActivity() fragment
        View view = inflater.inflate(R.layout.fragment_cart, container, false);
        unbinder = ButterKnife.bind(this, view);
        userId = (String) SPUtils.get(getActivity(), Constant.USER_ID, "");
        initView();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!choseDatas.isEmpty()) {
            choseDatas.clear();
        }
//        selectAllImg.setImageResource(R.mipmap.select);
        isChooseALL = false;
        SpannableString str = new SpannableString("合计:" + getString(R.string.rmb) + 0);
        str.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.fuzhu_red)), 3, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        moneyTv.setText(str);
        refresh();

    }

    private void getDatas() {
        OkGo.<String>post(Constant.CARTLIST)
                .tag(getActivity())
                .params("user", userId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        DealResult dealResult = new DealResult();
//                        List<CartBean> beans = dealResult.deal(getActivity(), response, new TypeToken<BaseBean<CartBean>>() {
//                        }.getType());
//                        if (beans.isEmpty()) {
//                            toShoping();
////                            return;
//                        }
//                        cartAdapter.addAll(beans);
//                        cartRecycler.refreshComplete(requestNum);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(getActivity(), getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    private void toShoping() {
        commitLl.setVisibility(View.GONE);
        cartRecycler.setVisibility(View.GONE);
        toshopingTv.setVisibility(View.VISIBLE);
        toshopingTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    public void initView() {
        SpannableString str = new SpannableString("合计:" + getString(R.string.rmb) + "0");
        str.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.fuzhu_red)), 3, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        moneyTv.setText(str);
        tvMiddleTitle.setText("购物车");
        cartAdapter = new CartAdapter(getActivity(), this);
        cartRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        cartAdapter.setDataList(datas);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(cartAdapter);
        cartRecycler.setAdapter(lRecyclerViewAdapter);
        cartRecycler.setPullRefreshEnabled(true);
        DividerDecoration divider = new DividerDecoration.Builder(getActivity())
                .setHeight(R.dimen.divider_height_1)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.app_bg_color)
                .build();
        cartRecycler.addItemDecoration(divider);
        initBanner();
        //设置下拉刷新
        cartRecycler.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
//        cartRecycler.refresh();
        //设置上拉加载更多
     /*   mainRecyclerview.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (page < totalPage) {
                    page++;

                } else {
                    mainRecyclerview.setNoMore(true);
                }
            }
        });
          */
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                startActivity(new Intent(getActivity(), VideoDetailActivity.class));
            }
        });

    }

    //创建header
    ImageView selectAllImg;

    private void initBanner() {
        CommonHeader footer = new CommonHeader(getActivity(), R.layout.footer_cart);
        LRecyclerView lRecyclerView = (LRecyclerView) footer.findViewById(R.id.recyclerView);
        ProductAdapter mAdapter = new ProductAdapter(getActivity());
        lRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        ArrayList<String> mDatas = new ArrayList<String>();
        for (int i = 0; i < 20; i++) {
            mDatas.add("");
        }
        mAdapter.setDataList(new ArrayList<GoodsBean>());
        footerLRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        lRecyclerView.setAdapter(footerLRecyclerViewAdapter);
        //divider
        GridSpacingItemDecoration gridSpacingItemDecoration = new GridSpacingItemDecoration(2, 20, true);
        lRecyclerView.setHasFixedSize(true);
        lRecyclerView.addItemDecoration(gridSpacingItemDecoration);
        lRecyclerView.setPullRefreshEnabled(false);
        lRecyclerView.setLoadMoreEnabled(false);
        CommonHeader header = new CommonHeader(getActivity(), R.layout.header_line);
        footerLRecyclerViewAdapter.addHeaderView(header);
//        selectAllImg = (ImageView) header.findViewById(R.id.select_all_img);

//        deleteAllTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dropCart("", 2);
//            }
//        });
        lRecyclerViewAdapter.addFooterView(footer);
    }

    private void handleAllCart(boolean isChoose) {
        for (CartBean bean : cartAdapter.getDataList()) {
            bean.setChoose(isChoose);
        }
        lRecyclerViewAdapter.notifyDataSetChanged();
        if (isChoose) {
            choseDatas.clear();
            choseDatas.addAll(cartAdapter.getDataList());
        } else {
            choseDatas.clear();
        }
        countMoney();
    }


    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private boolean isEdit = false;

    @OnClick({R.id.tv_choose, R.id.money_tv, R.id.commit_tv, R.id.toshoping_tv, R.id.ll_xfsc, R.id.tv_edit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_choose:
                break;
            case R.id.money_tv:
                break;
            case R.id.commit_tv:
                break;
            case R.id.toshoping_tv:
                break;
            case R.id.ll_xfsc:
                if (isChooseALL) {
                    imageXfsc.setImageResource(R.mipmap.select);
                    isChooseALL = false;
                } else {
                    imageXfsc.setImageResource(R.mipmap.select_true);
                    isChooseALL = true;
                }
                handleAllCart(isChooseALL);
                break;
            case R.id.tv_edit:
                TextPaint textPaint = tvEdit.getPaint();
                if (isEdit) {
                    tvEdit.setText("完成");
                    tvEdit.setTextColor(ContextCompat.getColor(getActivity(),R.color.fuzhu_red));
                    commitTv.setText("下单");
                    isEdit=false;
                } else {
                    tvEdit.setText("编辑");
                    commitTv.setText("删除");
                    moneyTv.setText("");
                    tvEdit.setTextColor(ContextCompat.getColor(getActivity(),R.color.second_textcolor));
                    isEdit=true;
                }
                break;
        }
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void addCart(CartBean item, int position) {
        cartAdapter.getDataList().get(position).setChoose(true);
        lRecyclerViewAdapter.notifyDataSetChanged();
        if (!choseDatas.contains(item)) {
            choseDatas.add(item);
        }
        countMoney();
        cartChoseAll();
    }

    @Override
    public void removeCart(CartBean item, int position) {
        cartAdapter.getDataList().get(position).setChoose(false);
        lRecyclerViewAdapter.notifyDataSetChanged();
        if (choseDatas.contains(item)) {
            choseDatas.remove(item);
        }
        countMoney();
        cartChoseAll();
    }

    /**
     * 购物车是否被全选
     */
    private void cartChoseAll() {
        List<CartBean> lists = cartAdapter.getDataList();
        if (lists.isEmpty()) {
            return;
        }
        for (CartBean bean : lists) {
            if (!bean.isChoose()) {
                imageXfsc.setImageResource(R.mipmap.select);
                return;
            }
        }
        imageXfsc.setImageResource(R.mipmap.select_true);
    }

    @Override
    public void deleteCart(CartBean item, int position) {
        dropCart(item.getRec_id(), 1);
    }

    public void dropCart(String id, int type) {
        //        1、删除购物车中某一个商品2、清空购物车
        DialogUtils.showProgressDlg(getActivity(), "");
        OkGo.<String>post(Constant.DROP_CART)
                .tag(getActivity())
                .params("user", userId)
                .params("rec_id", id)
                .params("type", type)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
//                        DealResult dealResult = new DealResult();
//                        BaseBean bean = dealResult.dealBaseRes(getActivity(), response);
//                        if (bean == null) {
//                            return;
//                        }
//                        if (bean.getStatus() == Constant.SUCESS) {
//                            ToastUtils.toastForShort(getActivity(), "删除成功");
//                            cartAdapter.clear();
//                            lRecyclerViewAdapter.notifyDataSetChanged();
//                            getDatas();
//                        } else {
//                            ToastUtils.toastForShort(getActivity(), "删除失败");
//                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(getActivity(), getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    private String receIds;

    private void countMoney() {
        if (choseDatas.isEmpty()) {
            SpannableString str = new SpannableString("合计:" + getString(R.string.rmb) + 0);
            str.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.fuzhu_red)), 3, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            moneyTv.setText(str);
            return;
        }
        float price = 0;
        receIds = "";
        for (CartBean bean : choseDatas) {
            float f = Float.parseFloat(bean.getSubtotal());
            price = price + f;
            receIds = receIds + bean.getRec_id() + ",";
        }
        if (receIds.endsWith(",")) {
            receIds = receIds.substring(0, receIds.length() - 1);
        }

        SpannableString str = new SpannableString("合计:" + getString(R.string.rmb) + price);
        str.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.fuzhu_red)), 3, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        moneyTv.setText(str);
    }

    /**
     * 刷新
     */
    public void refresh() {
        cartAdapter.clear();
        lRecyclerViewAdapter.notifyDataSetChanged();
        page = 1;
        getDatas();
    }

    //
    public void refresh1(int position, int number, String subtotal) {
        LogUtils.d("---" + position + number + subtotal);
        CartBean bean = cartAdapter.getDataList().get(position);
        bean.setGoods_number(number + "");
        bean.setSubtotal(subtotal);
        cartAdapter.getDataList().set(position, bean);
        lRecyclerViewAdapter.notifyItemChanged(lRecyclerViewAdapter.getAdapterPosition(false, position), "jdsjlzx");
        lRecyclerViewAdapter.notifyDataSetChanged();

    }
}
